<template>
	<div>
		<div class="search-box">
			<div class="search-item">
				<div class="search-content">
					<el-input placeholder="通过员工昵称搜索员工,记得回车哦..." clearable @change="keywordsChange"
						style="width: 300px;margin: 0px;padding: 0px;" size="mini" :disabled="advanceSearchViewVisible"
						@keyup.enter.native="searchEmp" prefix-icon="el-icon-search" v-model="keywords">
					</el-input>
				</div>
			</div>
		</div>
		<div class="form-edit-btns">
			<el-button type="primary" size="mini" style="margin-left: 5px" icon="el-icon-search" @click="searchEmp">搜索
			</el-button>
			<el-button slot="reference" type="primary" size="mini" style="margin-left: 5px"
				@click="showAdvanceSearchView"><i class="fa fa-lg"
					v-bind:class="[advanceSearchViewVisible ? faangledoubleup:faangledoubledown]"
					style="margin-right: 5px"></i>高级搜索
			</el-button>

			<el-button type="primary" size="mini" icon="el-icon-plus" @click="showAddEmpView">
				添加
			</el-button>



			<el-upload :show-file-list="false" accept="application/vnd.ms-excel" action="/sys/student/import"
				:on-success="fileUploadSuccess" :on-error="fileUploadError" :disabled="fileUploadBtnText=='正在导入'"
				:before-upload="beforeFileUpload" style="display: inline">
				<el-button size="mini" type="success" :loading="fileUploadBtnText=='正在导入'"><i
						class="fa fa-lg fa-level-up" style="margin-right: 5px"></i>{{fileUploadBtnText}}
				</el-button>
			</el-upload>


			<el-button type="primary" size="mini" icon="el-icon-download" @click="exportExcel">导出</el-button>
		</div>

		<el-main style="padding-left: 0px;padding-top: 0px">
			<div>
				<transition name="slide-fade">
					<div style="margin-bottom: 10px;border: 1px;border-radius: 5px;border-style: solid;padding: 5px 0px 5px 0px;box-sizing:border-box;border-color: #20a0ff"
						v-show="advanceSearchViewVisible">
						<el-row style="margin-top: 10px">
							<el-col :span="3">

								<el-select v-model="search_identity" placeholder="请选择" clearable="">
									<el-option label="普通用户" :value="1">
									</el-option>
									<el-option label="VIP用户" :value="2">
									</el-option>
								</el-select>

							</el-col>


							<el-col :span="3">

								<el-select v-model="search_period_id" placeholder="请选择">
									<el-option v-for="item in periodList" :key="item.id" :label="item.name"
										:value="item.id">
									</el-option>
								</el-select>

							</el-col>
							<el-col :span="4" :offset="4">
								<el-button size="mini" @click="cancelSearch">取消</el-button>
								<el-button icon="el-icon-search" type="primary" size="mini" @click="searchEmp">搜索
								</el-button>
							</el-col>
						</el-row>
					</div>
				</transition>
				<el-table :data="emps" v-loading="tableLoading" border stripe @selection-change="handleSelectionChange"
					size="mini" style="width: 100%">
					<el-table-column type="selection" align="left">
					</el-table-column>
					<el-table-column prop="name" label="昵称">
					</el-table-column>


					<el-table-column prop="period.name" label="分组">
					</el-table-column>


					<el-table-column prop="phone" label="电话号码">
					</el-table-column>


					<el-table-column prop="identity" :formatter="toIdentityLabel" label="身份"></el-table-column>

					<el-table-column label="操作">
						<template slot-scope="scope">
							<el-button type="text" @click="showEditEmpView(scope.row)" size="mini">编辑</el-button>
							<el-button type="text" @click="resetPhone(scope.row)" size="mini">重置</el-button>
							<el-button type="text" @click="deleteEmp(scope.row)" size="mini">删除</el-button>
							<el-button type="text" @click="showAssignCourseView(scope.row)" size="mini">关联</el-button>
						</template>
					</el-table-column>
				</el-table>
				<el-pagination background :page-size="10" :current-page="currentPage" @current-change="currentChange"
					layout="prev, pager, next" :total="totalCount">
				</el-pagination>
				<div class="form-edit-btns" style="float:right">
					<el-button type="danger" size="mini" v-if="emps.length>0" :disabled="multipleSelection.length==0"
						@click="deleteManyEmps">批量删除
					</el-button>
				</div>
			</div>
		</el-main>
		<el-dialog :title="dialogTitle" style="padding: 0px;" :close-on-click-modal="false"
			:visible.sync="dialogVisible">
			<el-form :model="emp" :rules="rules" ref="empForm" style="margin: 0px;padding: 0px;">



				<el-form-item label="昵称:" prop="name">
					<el-input prefix-icon="el-icon-edit" v-model="emp.name" size="mini" placeholder="请输入昵称"></el-input>
				</el-form-item>


				<el-form-item label="电话号码:" prop="phone">
					<el-input prefix-icon="el-icon-phone" v-model="emp.phone" size="mini" placeholder="电话号码...">
					</el-input>
				</el-form-item>


				<el-form-item label="分组" prop="period_id">
					<el-select v-model="emp.period_id" placeholder="请选择">
						<el-option v-for="item in periodList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>


				<el-form-item label="学生身份:" prop="identity">
					<el-radio-group v-model="emp.identity">
						<el-radio :label=1>普通用户</el-radio>
						<el-radio :label=2>vip用户</el-radio>
					</el-radio-group>
				</el-form-item>



				<el-form-item>
					<el-button size="mini" @click="cancelEidt">取 消</el-button>
					<el-button size="mini" type="primary" @click="addEmp('empForm')">确 定</el-button>
				</el-form-item>

			</el-form>
		</el-dialog>


		<el-dialog :title="dialogTitle" style="padding: 0px;" :close-on-click-modal="false"
			:visible.sync="relateCourseDialogVisible">
			<el-row :gutter="20">
			  <el-col :span="12">
				  <el-table ref="multipleTable" :data="courselist" tooltip-effect="dark" style="width: 100%"
				  	@selection-change="handleSelectionChangetwo">
				<!--  	<el-table-column type="selection" width="55">
				  	</el-table-column> -->
				  	<el-table-column label="课程ID" width="120">
				  		<template slot-scope="scope">{{ scope.row.id }}</template>
				  	</el-table-column>
				  	<el-table-column label="课程名称" width="120">
				  		<template slot-scope="scope">{{ scope.row.name }}</template>
				  	</el-table-column>
				  	<!-- <el-table-column label="课程名称" width="120">
				  		<template slot-scope="scope">{{ scope.row }}</template>
				  	</el-table-column> -->
				  	<!-- <el-table-column label="是否已经关联" width="120">
				  		<template slot-scope="scope">{{selt?"关联":"未关联"}}</template>
				  	</el-table-column> -->
				  	<el-table-column label="操作">
				  		<template slot-scope="scope">
				  
				  			<el-button type="text" @click="showAssignCourseViewtwo(scope.row)" size="mini">{{course_id==scope.row.id?"已选择":"选择"}}</el-button>
				  		</template>
				  	</el-table-column>
				  
				  </el-table>
				 <!-- <el-pagination background :small="true" :page-size="5" :current-page="currentPageone" @current-change="currentChangeone"
				  	layout="prev, pager, next" :total="totalCount">
				  </el-pagination> -->
			  </el-col>
			<el-col  :span="12">
				<el-table ref="multipleTable" :data="nuuuus" tooltip-effect="dark" style="width: 100%"
					@selection-change="handleSelectionChange">
					<!-- <el-table-column type="selection" width="55">
					</el-table-column> -->
					<el-table-column label="已选课程ID" width="120">
						<template slot-scope="scope">{{ scope.row.id }}</template>
					</el-table-column>
					<el-table-column label="课程名称" width="120">
						<template slot-scope="scope">{{ scope.row.name }}</template>
					</el-table-column>
					<el-table-column label="操作" width="120">
						<template slot-scope="scope">
						
							<el-button type="text" @click="deleteEmpyx(scope.row)" size="mini">删除</el-button>
						</template>
					</el-table-column>
				
				
				</el-table>
				<!-- <el-pagination :small="true" background :page-size="2" :current-page="currentPageone" @current-change="currentChangeone"
					layout="prev, pager, next" :total="totalCount">
				</el-pagination> -->
			</el-col>
			</el-row>
			
			
			<!-- <div style="margin-top: 20px">
	      <el-button @click="toggleSelection([tableData[1], tableData[2]])">切换第二、第三行的选中状态</el-button>
	      <el-button @click="toggleSelection()">取消选择</el-button>
	    </div> -->
			<el-form style="margin: 0px;padding: 0px;">
				<el-form-item>
					<el-button size="mini" @click="cancelRelateEdit">取 消</el-button>
					<el-button size="mini" type="primary" @click="relateCourse()">确 定</el-button>
				</el-form-item>
			</el-form>
		</el-dialog>
	</div>
</template>
<script>
	export default {
		data() {
			return {
				multipleSelectionkc:[],
				emps: [],
				keywords: '',
				props: {
					multiple: true
				},
				search_identity: '',
				search_period_id: '',
				fileUploadBtnText: '导入数据',
				beginDateScope: '',
				faangledoubleup: 'fa-angle-double-up',
				faangledoubledown: 'fa-angle-double-down',
				dialogTitle: '',
				multipleSelection: [],
				selectedList: [],
				depTextColor: '#c0c4cc',
				totalCount: -1,
				currentPage: 1,
				currentPageone:1,
				sizeone:10,
				roleList: [],
				periodList: [],
				famousCourseList: [],
				defaultProps: {
					label: 'name',
					isLeaf: 'leaf',
					children: 'children'
				},
				dialogVisible: false,
				relateCourseDialogVisible: false,
				disabled: true,
				tableLoading: false,
				advanceSearchViewVisible: false,
				showOrHidePop: false,
				showOrHidePop2: false,
				emp: {
					name: '',
					phone: '',
					identity: '',
					period_id: ''
				},
				rules: {
					name: [{
						required: true,
						message: '必填:昵称',
						trigger: 'blur'
					}],
					phone: [{
						required: true,
						message: '必填:电话号码',
						trigger: 'blur'
					}],
					identity: [{
						required: true,
						message: '必填:学生身份',
						trigger: 'blur'
					}],
					period_id: [{
						required: true,
						message: '必填:学生分组',
						trigger: 'blur'
					}],
				},
				tableData: [{
					date: '2016-05-03',
					name: '王小虎',
					address: '上海市普陀区金沙江路 1518 弄'
				}, {
					date: '2016-05-02',
					name: '王小虎',
					address: '上海市普陀区金沙江路 1518 弄'
				}, {
					date: '2016-05-04',
					name: '王小虎',
					address: '上海市普陀区金沙江路 1518 弄'
				}, {
					date: '2016-05-01',
					name: '王小虎',
					address: '上海市普陀区金沙江路 1518 弄'
				}, {
					date: '2016-05-08',
					name: '王小虎',
					address: '上海市普陀区金沙江路 1518 弄'
				}, {
					date: '2016-05-06',
					name: '王小虎',
					address: '上海市普陀区金沙江路 1518 弄'
				}, {
					date: '2016-05-07',
					name: '王小虎',
					address: '上海市普陀区金沙江路 1518 弄'
				}],
				multipleSelection: [],
				courseName: "",
				courselist: [],
				handleSelectiontwo: [],
				allClassCourseIds: [],
				course_id: '',
				multipleSelectiontwo: '',
				selt: false,
				arrcouse: [],
				nuuuus: []
			};
		},
		mounted: function() {
			this.loadEmps();
			this.loadPeriodList();
			// this.loadFamousList();
			this.queryCourse()
		},
		methods: {
			handleSelectionChangekc(val) {
							let that = this
							let un = []
							val.map(item => {
								un.push(item.id)
							})
							
							// console.log(jons)
							that.multipleSelectionkc = un;
							console.log(that.multipleSelectionkc)
						},
			noews() {
				var _this = this;
				console.log(this.emp.id)
				this.postRequest("/user/queryUserJoinCourse", {
					user_id: this.emp.id,
					page:this.currentPageone,
					size:3
				}).then(res => {
					let arrcouse = []
					if (res) {
						let auns = res.data.data.list
						// console.log(res)
						auns.map(item => {

							arrcouse.push(item.course_id)
						})
					}
					console.log(arrcouse)
					_this.arrcouse = arrcouse
					_this.queryCourse(arrcouse)
				})
			},
			queryCourse(arrcouse) {
				console.log(arrcouse)
				var _this = this
				let target = []
				let annus = []

				this.postRequest("/course/queryCourses", {
					name: this.courseName,
					is_famous: 1,
					// page:this.currentPageone,
					// size:this.sizeone
				}).then((resp) => {
					this.courselist = resp.data.data.arrays;
					this.courselist
					this.courselist.map(item => {
						target.push(item.id)
					})
					console.log(target)
					console.log(this.courselist)
// target是总的课的id
// A是已选课的ID
					function Check(A) {

						let i, j
						let totalmatches = 0
						for (i = 0; i < target.length; i++) {
							for (j = 0; j < A.length; ++j) {
								if (target[i] == A[j]) {
									// totalmatches++
									annus.push(i)
								}
							}
						}
// 得到已选课在总数字的I(位置)
						function unique(arr) {
							if (!Array.isArray(arr)) {
								console.log('type error!')
								return
							}
							var array = [];
							for (var i = 0; i < arr.length; i++) {
								if (array.indexOf(arr[i]) === -1) {
									array.push(arr[i])
								}
							}
							return array;
						}
						annus = unique(annus)
						let nuuuus = []
						_this.courselist.map((item, index) => {
							console.log(index)
							for (var v = 0; v < annus.length; v++) {
								// console.log(index)
								// console.log(annus[v])
								if (annus[v] == index) {
									nuuuus.push(Object.assign(item, {
										bbw: true
									}))
								}
							}


						})

						_this.nuuuus = nuuuus
						console.log(nuuuus)
						console.log(annus)
						if (totalmatches > 0) {
							console.log(12121212)

						} else {
							console.log(34512121212)
						}
					}
					var okns = []
					Check(arrcouse)
					for (var c in this.courselist) {
						this.allClassCourseIds.push(this.courselist[c].id);
					}
				});
			},
			toggleSelection(rows) {
				if (rows) {
					rows.forEach(row => {
						this.$refs.multipleTable.toggleRowSelection(row);
					});
				} else {
					this.$refs.multipleTable.clearSelection();
				}
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
			},
			handleSelectionChangetwo(val) {
				let that = this
				let un = []
				val.map(item => {
					un.push(item.id)
				})
				un = un.join(",")
				var jons = {}
				for (var i = 0; i < un.length; i++) {
					jons[i] = un[i];
				}
				JSON.stringify(jons)
				console.log(jons)
				that.multipleSelectiontwo = un;
				console.log(that.multipleSelectiontwo)
			},
			toIdentityLabel(row) {
				if (row.identity == 1) return "普通用户";
				if (row.identity == 2) return "vip用户";
			},

			exportExcel() {
				location.href = "/sys/student/export?keywords=" + this.keywords + "&identity=" + this.search_identity +
					"&period_id=" + this.search_period_id;
			},

			fileUploadSuccess(response, file, fileList) {
				if (response) {
					this.$message({
						type: response.status,
						message: response.msg
					});
				}
				this.loadEmps();
				this.fileUploadBtnText = '导入数据';
			},
			fileUploadError(err, file, fileList) {
				this.$message({
					type: 'error',
					message: "导入失败!"
				});
				this.fileUploadBtnText = '导入数据';
			},
			beforeFileUpload(file) {
				this.fileUploadBtnText = '正在导入';
			},


			loadPeriodList() {
				var _this = this;
				this.tableLoading = true;
				this.getRequest("/period/list?page=" + this.currentPage + "&size=1000").then(resp => {
					this.tableLoading = false;
					if (resp && resp.status == 200) {
						var data = resp.data;
						_this.periodList = data.data.arrays;
					}
				})
			},
			loadFamousList() {
				var _this = this;
				this.tableLoading = true;
				this.postRequest("/front/course/famous_list").then(resp => {
					this.tableLoading = false;
					if (resp && resp.status == 200) {
						var data = resp.data;
						_this.famousCourseList = data.data.arrays;
						// _this.arrcouse
					}
				})
			},

			cancelSearch() {
				this.advanceSearchViewVisible = false;
				this.emptyEmpData();
				this.beginDateScope = '';
				this.loadEmps();
			},
			showAdvanceSearchView() {
				this.advanceSearchViewVisible = !this.advanceSearchViewVisible;
				this.keywords = '';
				if (!this.advanceSearchViewVisible) {
					this.emptyEmpData();
					this.beginDateScope = '';
					this.loadEmps();
				}
			},
			handleSelectionChange(val) {
				this.multipleSelection = val;
				console.log(val)
			},
			deleteManyEmps() {
				this.$confirm('此操作将删除[' + this.multipleSelection.length + ']条数据, 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					var ids = '';
					for (var i = 0; i < this.multipleSelection.length; i++) {
						ids += this.multipleSelection[i].id + ",";
					}
					this.doDelete(ids);
				}).catch(() => {});
			},
			deleteEmp(row) {
				this.$confirm('此操作将永久删除[' + row.name + '], 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.doDelete(row.id);
				}).catch(() => {});
			},
			deleteEmpyx(row) {
				var that = this
				console.log(row)
				this.$confirm('此操作将永久删除[' + row.name + '], 是否继续?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					console.log(this.emp.id)
					console.log(row)
					this.postRequest("/user/delCourse", {
						user_id: this.emp.id,
						course_id: row.id
					}).then(resp => {
						console.log(resp)
						that.noews()
					})
				}).catch(() => {});
			},
			doDelete(ids) {
				this.tableLoading = true;
				var _this = this;
				this.deleteRequest("/sys/user/" + ids).then(resp => {
					_this.tableLoading = false;
					if (resp && resp.status == 200) {
						var data = resp.data;
						_this.$message({
							type: data.status,
							message: data.msg
						});
						_this.loadEmps();
					}
				})
			},



			keywordsChange(val) {
				this.currentPage = 1;
				if (val == '') {
					this.loadEmps();
				}
			},
			searchEmp() {
				this.currentPage = 1;
				this.loadEmps();
			},
			currentChange(currentChange) {
				this.currentPage = currentChange;
				this.loadEmps();
			},
			currentChangeone(currentChangeone) {
				this.currentPageone = currentChangeone;
				this.queryCourse();
			},
			loadEmps() {
				var _this = this;
				this.tableLoading = true;
				this.getRequest("/sys/student/list?page=" + this.currentPage + "&size=10&keywords=" + this.keywords +
					"&identity=" + this.search_identity + "&period_id=" + this.search_period_id).then(resp => {
					this.tableLoading = false;
					console.log(resp)
					if (resp && resp.status == 200) {
						var data = resp.data;
						_this.emps = data.data.arrays;

						_this.totalCount = data.data.count;
					}
				})
			},
			addEmp(formName) {
				var _this = this;

				this.$refs[formName].validate((valid) => {
					if (valid) {
						if (_this.emp.id) {
							//更新
							this.tableLoading = true;
							this.postRequest("/sys/user/update", _this.emp).then(resp => {
								_this.tableLoading = false;
								if (resp && resp.status == 200) {
									var data = resp.data;
									_this.$message({
										type: data.status,
										message: data.msg
									});
									_this.dialogVisible = false;
									_this.emptyEmpData();
									_this.loadEmps();
								}
							})
						} else {
							//添加
							this.tableLoading = true;
							this.postRequest("/sys/student/add", _this.emp).then(resp => {
								_this.tableLoading = false;
								if (resp && resp.status == 200) {
									var data = resp.data;
									_this.$message({
										type: data.status,
										message: data.msg
									});
									_this.dialogVisible = false;
									_this.emptyEmpData();
									_this.loadEmps();
								}
							})
						}
					} else {
						return false;
					}
				});
			},



			relateCourse() {
				var _this = this;
				this.postRequest("/user/queryUserJoinCourse", {
					user_id: this.emp.id
				}).then(res => {
					// 请求已经关联的课程
					let arrcouse = []
					if (res) {
						let auns = res.data.data.list
						// console.log(res)
						auns.map(item => {

							arrcouse.push(item.course_id)
						})
					}
					console.log(arrcouse)
					_this.arrcouse = arrcouse
					_this.queryCourse(arrcouse)
				})

				//更新
				// let an ={}
				// an.user_id = this.emp.id
				// an.course_id =this.multipleSelectiontwo
				// console.log(an)
				if(!this.course_id){
					_this.$message({
						type:'filed' ,
						message:"未选择课程"
					});
				}else{
					this.tableLoading = true;
					var courses_str = JSON.stringify(this.selectedList);
					this.postRequest("/user/addCourse", {
						user_id: this.emp.id,
						course_id: this.course_id
					}).then(resp => {
						console.log(resp)
						_this.tableLoading = false;
						if (resp && resp.status == 200) {
							console.log(resp)
							var data = resp.data;
							_this.$message({
								type: data.status,
								message: data.msg
							});
							_this.relateCourseDialogVisible = false;
							_this.emptyEmpData();
							_this.loadEmps();
						}
					})
					_this.course_id = ""
				}
				
				
			},


			cancelEidt() {
				this.dialogVisible = false;
				this.emptyEmpData();
			},
			cancelRelateEdit() {
				this.relateCourseDialogVisible = false;
				this.emptyEmpData();
			},
			resetPhone(row) {
				this.tableLoading = true;
				var _this = this;
				this.postRequest("/sys/user/reset", {
					id: row.id
				}).then(resp => {
					_this.tableLoading = false;
					if (resp && resp.status == 200) {
						var data = resp.data;
						_this.$message({
							type: data.status,
							message: data.msg
						});
					}
				})
			},
			showEditEmpView(row) {

				this.emptyEmpData();

				this.disabled = true;

				this.dialogTitle = "编辑";
				this.emp.name = row.name;
				this.emp.id = row.id;
				this.emp.phone = row.phone;
				this.emp.identity = row.identity;
				this.emp.period_id = row.period_id;
				// this.emp = row;

				// delete this.emp.roles;
				this.dialogVisible = true;
			},


			showAssignCourseView(row) {

				this.emptyEmpData();

				this.dialogTitle = "关联名师课堂";

				this.emp.name = row.name;
				this.emp.id = row.id;
				this.emp.phone = row.phone;
				this.emp.identity = row.identity;
				this.emp.period_id = row.period_id;
				this.relateCourseDialogVisible = true;
				this.noews()
				// var _this = this;

				// this.postRequest("/sys/student/famous/course", {
				// 	user_id: row.id,
				// }).then(resp => {
				// 	_this.tableLoading = false;
				// 	if (resp && resp.status == 200) {
				// 		var data = resp.data;
				// 		var join_courses = data.data.arrays;
				// 		if (join_courses != null) {
				// 			for (var ind = 0; ind < join_courses.length; ind++) {
				// 				_this.selectedList.push(join_courses[ind].course_id)
				// 			}
				// 		}
				// 	}
				// })
			},
			showAssignCourseViewtwo(row) {
				console.log(row)
				this.course_id = row.id
				
				// if(this.course_id !== ''){
					
				// }
			},
			showAddEmpView() {
				this.dialogTitle = "添加";
				this.dialogVisible = true;
				this.disabled = false;
				var _this = this;
			},
			emptyEmpData() {
				this.emp = {
					name: '',
					phone: '',
					identity: '',
					period_id: ''
				};
				this.selectedList = [];
			}
		}
	};
</script>
<style scoped>
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
	}
</style>
